package com.nwpu.server.authserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.nwpu.server.authserver.dao.CaptchaDao;
import com.nwpu.server.authserver.entity.CaptchaEntity;
import com.nwpu.server.authserver.service.CaptchaService;
import com.nwpu.server.common.exception.RRException;
import com.nwpu.server.common.response.PageUtils;
import com.nwpu.server.common.response.Query;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Map;

/**
 * @Author: YuXingZh
 * @Date: Created in 20:02 2022-04-17
 * @Description:
 */

@Service("captchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaDao, CaptchaEntity> implements CaptchaService {
    @Autowired
    private Producer producer = null;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CaptchaEntity> page = this.page(
                new Query<CaptchaEntity>().getPage(params),
                new QueryWrapper<CaptchaEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 生成图片验证码
     *
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }

        //生成文字验证码
        String code = producer.createText();
        CaptchaEntity captchaEntity = new CaptchaEntity();
        captchaEntity.setCode(code);
        captchaEntity.setUuid(uuid);

        // 五分钟后后过期
        captchaEntity.setExpireTime(DateUtils.addMonths(new Date(), 1));
        this.save(captchaEntity);
        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String captcha) {
        CaptchaEntity captchaEntity = this.getOne(new QueryWrapper<CaptchaEntity>().eq("uuid", uuid));
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        this.removeById(uuid);

        if(captchaEntity.getCode().equalsIgnoreCase(captcha) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }
}